package com.example.myapp.ADO;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Comment;
import com.example.myapp.Model.Fensi;
import com.example.myapp.Model.User;
import com.example.myapp.R;


import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class CommentAdaper extends BaseAdapter {

    private Context context;
    private  List<String> gzlist=new ArrayList<>();//关注
    private List<Comment> Commentlist;
    private LayoutInflater mInflater;
    private ShapeLoadingDialog shapeLoadingDialog;
    //自定义adaper开始
    public CommentAdaper(Context context, List<Comment> Commentlist, List<String> article) {
        this.context = context;
        this.Commentlist = Commentlist;
        this.gzlist = article;
        mInflater = LayoutInflater.from(context);//初始化

    }
    @Override
    public boolean areAllItemsEnabled() {
        return super.areAllItemsEnabled();
    }

    @Override
    public int getCount() {
        return Commentlist.size();
    }

    @Override
    public Object getItem(int i) {
        return Commentlist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        view = mInflater.inflate(R.layout.commentitem, null);
        CircleImageView icon = view.findViewById(R.id.art_icon);
        TextView username = view.findViewById(R.id.art_username);
        TextView comment = view.findViewById(R.id.art_comment);
        TextView art_guanzhu = view.findViewById(R.id.art_guanzhu);
        Glide.with(context).load(Commentlist.get(i).getAuthor().getIcon().getUrl()).into(icon);// CircleImageView.显示网络图片特殊方法
        username.setText(Commentlist.get(i).getAuthor().getUsername());
        comment.setText(Commentlist.get(i).getContent());
        /**初始化关注*/
        if (gzlist.contains(Commentlist.get(i).getAuthor().getObjectId())){
            art_guanzhu.setText("已关注");
            Log.w("dddd","当前用户"+ BmobUser.getCurrentUser(User.class).getObjectId());
            art_guanzhu.setTextColor(Color.parseColor("#CCCCCC"));//已经关注的颜色
        }
        if(Commentlist.get(i).getAuthor().getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
            art_guanzhu.setText("删除评论");
            art_guanzhu.setTextColor(Color.parseColor("#FF5722"));//橘色
        }
        art_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //判断是否已经关注
                if(art_guanzhu.getText().toString().equals("关注")){
                    Log.w("aaaa",""+Commentlist.get(i).getAuthor().getObjectId()+Commentlist.get(i).getAuthor().getUsername());
                   gzlist.add(Commentlist.get(i).getAuthor().getObjectId());//保存到当前关注数据刷新用，因为后台来不及刷新
                    art_guanzhu.setTextColor(Color.parseColor("#CCCCCC"));//橘色
                    art_guanzhu.setText("已关注");
                    saveFriend(Commentlist.get(i).getAuthor().getObjectId());//添加好友关联
                }
                else if(art_guanzhu.getText().toString().equals("已关注")){
                gzlist.remove(Commentlist.get(i).getAuthor().getObjectId());
                art_guanzhu.setTextColor(Color.parseColor("#FF5722"));//橘色
                art_guanzhu.setText("关注");
                    //Log.w("aaaa",""+Commentlist.get(i).getAuthor().getObjectId()+Commentlist.get(i).getAuthor().getUsername());
                 clearFriend(Commentlist.get(i).getAuthor().getObjectId());//取消关注

                }
//(artlist_guanzhu.getText().toString().equals("删除评论"))
                else {
                     clearComment(Commentlist.get(i).getObjectId());
                    Commentlist.remove(i);
                    notifyDataSetChanged();
                }

            }
        });//关注按钮

        return view;
    }


    /**删除评论*/
   private void clearComment(String commentid){
       openLoading();
       Comment p2 = new Comment();
       p2.setObjectId(commentid);
       p2.delete(new UpdateListener() {
           @Override
           public void done(BmobException e) {
               if(e==null){
                   Log.w("aaaa","删除成功:"+p2.getUpdatedAt());
                   notifyDataSetChanged();
                   closeLoading();
               }else{
                   Log.w("aaaa","删除失败：" + e.getMessage());
               }
           }

       });

   }
    /** 添加多对多好友*/
    //填写被当前用户要关注的用户id
    private void saveFriend(String userObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            User user1 = new User();//创建被关注用户并且给上Id
            user1.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user1);//装进去当前用户;
            user.setFriend(relation);
            user.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "添加好友成功");
                        notifyDataSetChanged();
                        closeLoading();
                        saveFensi(userObjId);
                    } else {
                        Log.w("aaaa", "添加好友失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }
    /** 删除多对多*/
    //填写被当前用户要关注的用户id
    private void clearFriend(String userObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            User user1 = new User();//创建被关注用户并且给上Id
            user1.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.remove(user1);//装进去当前用户;
            user.setFriend(relation);
            user.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "取消关注成功");
                      notifyDataSetChanged();
                      closeLoading();
                        clearFensi(userObjId);
                    } else {
                        Log.w("aaaa", "取消关注失败：" + e.getMessage());

                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }

    /**添加一对多粉丝*/
    private void saveFensi(String userID) {
        User user = new User();
        user.setObjectId(userID);//测试文本1的文章id
        final Fensi fensi = new Fensi();
        fensi.setUser(user);
        fensi.setFensi(BmobUser.getCurrentUser(User.class));
        fensi.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "添加粉丝成功！");
                } else {
                    Log.w("aaaa", "添加粉丝成功失败：" + e.getMessage());
                }
            }

        });
    }

    private  void clearFensi(String userID){
        BmobQuery<Fensi> eq1 = new BmobQuery<>();
        eq1.addWhereEqualTo("user",userID);
        BmobQuery<Fensi> eq2 = new BmobQuery<>();
        eq2.addWhereEqualTo("fensi", BmobUser.getCurrentUser(User.class).getObjectId());
        List<BmobQuery<Fensi>> queries = new ArrayList<BmobQuery<Fensi>>();
        queries.add(eq1);
        queries.add(eq2);
        //查询符合整个and条件的人
        BmobQuery<Fensi> addquery = new BmobQuery<Fensi>();
        addquery.and(queries);
        addquery.findObjects(new FindListener<Fensi>() {
            @Override
            public void done(List<Fensi> object, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "查询粉丝成功："+object.get(0).getObjectId() );
                    Fensi p2 = new Fensi();
                    p2.setObjectId(object.get(0).getObjectId());
                    p2.delete(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                Log.w("aaaa", "删除粉丝成功:"+p2.getUpdatedAt());
                            }else{
                                Log.w("aaaa", "删除粉丝失败：" + e.getMessage());
                            }
                        }
                    });

                } else {
                    Log.w("aaaa", "查询粉丝失败："+e.getMessage() );
                }
            }
        });

    }

    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(context)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
        shapeLoadingDialog.dismiss();
    }


}
